import {
	defineStore
} from 'pinia'
import {
	ref,
	computed
} from 'vue'
import {
	getSite,
	addSite,
	editSite,
	delSite,
	getCartData,
	commitOrder,
	getOrder,
	queryPayOrder
} from '../api/cart.api.js'
import { getOrderId } from '../utils/util.js'
export const useCartStore = defineStore(
	'cart',
	() => {

		const siteData = ref([]) // 地址
		const selectSiteData = ref({}) // 选中地址
		const statu = ref() // 页面为添加页面还是编辑页面
		const id = ref() // 地址id
		const cartData = ref([]) // 购物车商品
		const cartDataId = ref() // 购物车商品id
		// 订单详情
		const order_id = ref() // 订单id
		const orderGood = ref([])   // 订单商品信息
		const orderInfo = ref({})  // 订单信息
		const orderCode = ref()  // 订单状态码
		

		const newSite = ref({
			name: '',
			tel: '',
			province: '',
			city: '',
			county: '',
			addressDetail: '',
			postalCode: '',
			isDefault: '',
			areaCode: ''
		})

		// 获取地址数据
		const getSiteData = async () => {
			let result = await getSite()
			siteData.value = result
			// 获取数据时选中地址为默认地址
			if (JSON.stringify(selectSiteData.value) === '{}') {
			  selectSiteData.value = siteData.value.find(item => item.isDefault);
			}
		}

		// 选择地址
		const selectSite = (id) => {
			selectSiteData.value = siteData.value.filter(item => item.id === id)[0]
			uni.switchTab({
				url: '/pages/cart/cart'
			})
		}

		// 删除地址
		const delSiteData = async () => {
			await delSite(id.value)
			if(selectSiteData.value.id == id.value){
				selectSiteData.value = {}
			}
			clearSite()
			goSite()
			getSiteData()
		}
		
		const clearSite = () => {
			newSite.value = {
				name: '',
				tel: '',
				province: '',
				city: '',
				county: '',
				addressDetail: '',
				postalCode: '',
				isDefault: '',
				areaCode: ''
			}
		}

		// 保存
		const keep = async () => {
			let result = await addSite(newSite.value)
			clearSite()
			goSite()
			getSiteData()
		}

		// 提交
		const put = async () => {
			await editSite(id.value, newSite.value)
			clearSite()
			goSite()
			getSiteData()
		}

		// 跳转地址页面
		const goSite = () => {
			uni.navigateTo({
				url: '/pages/site/site'
			})
		}

		// 跳转添加地址页面
		const goAddSite = (id,title) => {
			uni.navigateTo({
				url: `/pages/addsite/addsite?id=${id}&title=${title}`
			})
		}
		// 添加购物车
		const addCartData = (data) => {
			let index = cartData.value.findIndex(item => item.id === data.id)
			if (index > -1) {
				cartData.value[index].count += data.count
			} else {
				cartData.value.push(data)
			}

			let ids = cartData.value.map((item) => item.id).join(',')
			if (ids.charAt(ids.length - 1) === ',') {
				return ids.substring(0, ids.length - 1)
			}
			if (ids.charAt(0) === ',') {
				return ids.substring(1)
			}
			cartDataId.value = ids
		}
		
		// 总数量
		let countAll = computed(() => {
			let countData = 0
			cartData.value.forEach(item => {
				if(item.selected){
					countData += item.count
				}
			})
			return countData
		})
		
		// 总价格
		let priceAll = computed(() => {
			let priceData = 0
			cartData.value.forEach(item => {
				if(item.selected) {
					priceData += (item.count * item.price)
				}
			})
			return priceData
		})
		
		// 角标
		const updateTabBarBadge = () => {
			const cartTabIndex = 2;

			if (countAll.value > 0) {
				uni.setTabBarBadge({
					index: cartTabIndex,
					text: countAll.value.toString()
				})
			} else {
				uni.removeTabBarBadge({
					index: cartTabIndex
				})
			}
		}
		// 获取购物车数据
		const getCartPageData = async () => {
			if (cartData.value.length > 0) {
				let {
					message
				} = await getCartData(cartDataId.value)
				
				cartData.value.forEach(cartItem => {
					message.forEach(mesItem => {
						if(cartItem.id === mesItem.id) {
							cartItem.title = mesItem.title
							cartItem.imgurl = mesItem.thumb_path
						}
					})
				})
				
			}
		}
		// 提交订单请求
		const submitOrder = async () => {
			order_id.value = getOrderId()
			// 准备订单参数
			let orderData = {
				order_id: order_id.value,
				address_id: selectSiteData.value.id,
				total_price: priceAll.value,
				number: countAll.value,
				goods_ids: cartDataId.value,
			}
			// 提交订单
            await commitOrder(orderData)
			// 获取订单商品数据
			let { message } = await getCartData(cartDataId.value)
			orderGood.value = message
			// 获取订单详情
			orderInfo.value = await getOrder(order_id.value)
			// 查询支付结果
			let { code } = await queryPayOrder(order_id.value)
			orderCode.value = code
		}
		
		// 取消订单重发请求
		const reSubmitOrder = async () => {
			// 获取订单商品数据
			let { message } = await getCartData(cartDataId.value)
			orderGood.value = message
			// 获取订单详情
			orderInfo.value = await getOrder(order_id.value)
		}
		return {
			// 数据
			siteData,
			selectSiteData,
			statu,
			id,
			cartData,
			cartDataId,
			newSite,
			countAll,
			priceAll,
			order_id,
			orderGood,
			orderInfo,
			orderCode,
			// 方法
			getSiteData,
			goSite,
			selectSite,
			goAddSite,
			keep,
			put,
			delSiteData,
			addCartData,
			updateTabBarBadge,
			getCartPageData,
			clearSite,
			submitOrder,
			reSubmitOrder
			
		}
	}, {
		persist: {
			storage: {
				getItem(key) {
					return JSON.parse(uni.getStorageSync(key)); // 手动替代 destr
				},
				setItem(key, value) {
					uni.setStorageSync(key, JSON.stringify(value));
				},
			},
		}
	}
)